#!/bin/bash

set -e

# 简化日志函数
log() { echo "⏰ [$(date +'%H:%M:%S')] $1" >&2; }
error() { echo "❌ [ERROR] $1" >&2; exit 1; }

# 检查 Docker
check_docker() {
    log "🔍 检查 Docker 服务..."
    ! docker info >/dev/null 2>&1 && error "Docker 未运行或无法访问"
    log "✅ Docker 服务运行正常。"
}

# 解压主包
unpack_package() {
    local package_file="$1" temp_dir="$2"
    log "📦 解压主包: $package_file 到 $temp_dir"
    tar xzf "$package_file" -C "$temp_dir"
}

# 导入应用目录
import_app() {
    local app_tar_file="$1" target_dir="$2"
    log "📂 导入应用目录: $app_tar_file 到 $target_dir"
    mkdir -p "$target_dir"
    tar xzf "$app_tar_file" -C "$target_dir" --strip-components=1
}

# 导入数据卷
import_volume() {
    local volume_tar_file="$1" volume_name="$2"
    log "💾 导入数据卷: $volume_name (来自 $volume_tar_file)"

    if docker volume inspect "$volume_name" >/dev/null 2>&1; then
        read -p "数据卷 '$volume_name' 已存在。是否覆盖? (y/N): " confirm_overwrite
        if [[ "$confirm_overwrite" != [yY] ]]; then
            log "跳过数据卷 '$volume_name' 的导入。"
            return 0
        fi
        log "删除现有数据卷 '$volume_name'..."
        docker volume rm "$volume_name" >/dev/null
    fi

    log "创建数据卷 '$volume_name'..."
    docker volume create "$volume_name" >/dev/null

    log "导入数据到数据卷 '$volume_name'..."
    docker run --rm -v "$volume_name:/data" -v "$(dirname "$volume_tar_file"):/backup" alpine \
        sh -c "tar xzf /backup/$(basename "$volume_tar_file") -C /data"
    log "✅ 数据卷 '$volume_name' 导入成功。"
}

# 主函数
main() {
    echo "🐳 === Docker Compose 应用解包工具 === 🐳"
    echo

    check_docker

    read -p "📦 请输入待解包的 .tar.gz 文件路径: " package_file
    [[ ! -f "$package_file" ]] && error "文件不存在: $package_file"

    # 创建临时目录
    local temp_dir
    temp_dir="$(mktemp -d -t docker-unpack-XXXXXX)"
    log "创建临时目录: $temp_dir"
    trap "log '清理临时目录: $temp_dir'; rm -rf '$temp_dir'" EXIT

    unpack_package "$package_file" "$temp_dir"

    echo
    echo "📋 === 解包摘要 ==="
    echo "📦 源文件: $package_file"
    echo "📁 临时解压目录: $temp_dir"

    # 查找应用目录包
    local app_tar_found=false
    for f in "$temp_dir"/*_app.tar.gz; do
        if [[ -f "$f" ]]; then
            app_tar_file="$f"
            app_tar_found=true
            break
        fi
    done

    if ! $app_tar_found; then
        error "在解压包中未找到应用目录文件 (*_app.tar.gz)。"
    fi

    local default_app_dir="$(pwd)/$(basename "${app_tar_file%_app.tar.gz}")"
    read -p "📂 请输入应用目录解压目标路径 [$default_app_dir]: " target_app_dir
    [[ -z "$target_app_dir" ]] && target_app_dir="$default_app_dir"

    echo "应用目录将解压到: $target_app_dir"

    # 查找数据卷包
    local volume_tar_files=("$temp_dir"/*.tar.gz)
    # 过滤掉应用目录包
    volume_tar_files=( "${volume_tar_files[@]/$app_tar_file}" )

    echo "💾 发现数据卷包:"
    if [[ ${#volume_tar_files[@]} -eq 0 || (${#volume_tar_files[@]} -eq 1 && -z "${volume_tar_files[0]}") ]]; then
        echo "   └── 无"
    else
        for vol_file in "${volume_tar_files[@]}"; do
            [[ -n "$vol_file" ]] && echo "   └── $(basename "$vol_file")"
        done
    fi
    echo

    read -p "✅ 确认执行? (y/N): " confirm
    [[ "$confirm" != [yY] ]] && exit 0

    # 执行解包和导入
    import_app "$app_tar_file" "$target_app_dir"

    for vol_file in "${volume_tar_files[@]}"; do
        if [[ -f "$vol_file" ]]; then
            volume_name="$(basename "${vol_file%.tar.gz}")"
            import_volume "$vol_file" "$volume_name"
        fi
    done

    echo
    echo "🎉 === 解包完成! ==="
    echo "✨ 应用和数据卷已成功导入! ✨"
}

# 运行主函数
main "$@"